/**
 * 	 data-initable="yes"    未指定参数时，需要处理的表格标识
 *	 data-paginationId=""   页面内的分页栏模版的id
 *   data-paginationUrl=""	分页栏的模版地址			
 *   data-toolBarId=""			工具栏的模版id
 *   data-toolBarUrl=""			工具栏的模版地址
 *   data-height=""					表格的高度
 *   data-minHeight=""			表格内容区的最小高度
 *   data-order=""				是否启用排序功能，0：不排序，1：排序
 * 	 data-sort-server= ""		是否请求后台查询排序：0：不请求。1：请求
 * 
 * 单个表格初始化可使用 new MaxTable(jdom);jdom为jQuery，或dom对象
 * 单个表格根据参数重置表格
 * 	var Ot = new MaxTable(jdom);
 * 	Ot.reflesh([height]);
 * 	
 * 	停止重置刷新
 * Ot.stopResize();
 * 多表格可以使用MaxTableInit(connection); connection为jQuery对象的集合
 * 
 * V0.6 说明：
 * 	1、新增表头的模拟点击事件，
 * 		只支持 给原table绑定onclick，ondblclick,onchange等事件
 * 		不支持jquery绑定的事件
 *  2、当MazTableInit方法没有传参数时，默认调用页面内所有的table[data-initable='yes']的集合
 * 	3、原表格保留，通过jQuery的wrap，before,after等方法改变其html所在的位置
 * 	4、可通过外部修改原表格的data-height的高度来做浏览器的自适应
 * 	5、如要修改插件自带样式，必须采用权重值更高的!important或表格的外包裹标签设置id，并通过#id来修改对应的css样式
 * 
 *	Ahthor：MaxJh
 * 	Copyright：MaxJh
 * 	Version：v0.6
 */
;
(function(win, $) {
	var OTable = function(obj) {
		var __this = this;
		this.target = $(obj);
		this.hasCaption = this.target.find("caption").length > 0 ? true : false;
		this.hasThead = this.target.find("thead").length > 0 ? true : false;
		this.hasTfoot = this.target.find("tfoot").length > 0 ? true : false;
		this.initParm();
		this.tableWraper = $("<div class='maxTableWarper'></div>");
		this.toolbar = $("<div class='maxTable_toolbar'></div>");
		this.caption = $("<div class='maxTable_caption'></div>");
		this.container = $("<div class='maxTable_container'></div>");
		this.header = $("<div class='maxTable_header'></div>");
		this.body = $("<div class='maxTable_body'></div>");
		this.footer = $("<div class='maxTable_footer'></div>");
		this.pagination = $("<div class='maxTable_pagination'></div>");
		this.getClass();
		this.getId();
		this.initStyle(__this.iniTable());
		return this;
	};

	OTable.CSSSTYLE = "<style id='tableInitSty'>" +
		"table[data-initable='yes']>thead {background: #cbcbcb;}" +
		".maxTable_container {position: relative;border: 1px solid #ddd;}" +
		".maxTable_header{position:absolute;top:0;left:0;right:0px;background:#ebebeb;width:100%;}" +
		".maxTable_header>table {background: #cbcbcb;width:100%;}" +
		".maxTable_caption>.table,.maxTable_header>.table,.maxTable_body>.table,.maxTable_footer>.table{margin-bottom:0px!important;}" +
		".maxTable_caption{margin-bottom:-1px;}" +
		".maxTable_body{overflow-y:auto;border-bottom: 1px solid #ddd;}" +
		".maxTable_footer{position:absolute;left:0;right:0px;bottom:0px;background:#ebebeb;}" +
		".maxTable_pagination{clear:both;zoom:1;overflow:hidden;}" +
		".maxTable_pagination .foot_nav{position:static;}" +
		"caption{background:#ddd;color:#333;text-indent:0.5em;}" +
		"</style>";

	OTable.CHECKBOX_CLASS = {
		headCheckBox: "js_maxheadCheck",
		headTriggerCheckBox: "js_maxbodyCheckTrigger",
		bodyCheckBox: "js_maxbodyCheck"
	}

	OTable.ID_COUNT = 0;

	OTable.ORDER_SPAN_CLASS = "js_orderSpanTrigger";
	OTable.CLASS_COMMON = '';
	OTable.ORDER = {
		NO_ORDER: 0,
		ASC: 1,
		DESC: 2,
	}
	
	OTable.SORT_CALLBACK = null;
	
	OTable.prototype = {
		initStyle: function(cb) {
			var head = $(document).find("head")
			if(head.find("style#tableInitSty").length == 0) {
				head.append(OTable.CSSSTYLE);
			};
			cb && cb();
		},
		//根据属性获取参数
		getParmByAttr: function(attr) {
			return this.target.attr("data-" + attr) || this.target.data(attr);
		},
		//初始化，从页面上获取设定的参数
		initParm: function() {
			var _this = this;
			_this.config = {};
			_this.config.height = _this.getParmByAttr("height"); //表格的高度
			_this.config.paginationUrl = _this.getParmByAttr("paginationUrl"); //分页栏模版id，优先级大于url
			_this.config.paginationId = _this.getParmByAttr("paginationId"); //分页栏模版url
			_this.config.toolBarId = _this.getParmByAttr("toolBarId"); //工具栏模版id，优先级大于url
			_this.config.toolBarUrl = _this.getParmByAttr("toolBarUrl"); //工具栏模版url
			_this.config.minHeight = _this.getParmByAttr("minHeight"); //表格内容区域的最小高度，默认最小140px
			/*_this.config.outTime = _this.getParmByAttr("outTime") || 10000;					//数据加载的最长时间，默认10s，在这个时间内，会不停的执行setInterval方法来使表格自适应
			 */
			_this.config.outTime = _this.getParmByAttr("outTime") || 1000; //数据加载的最长时间，默认1s，在这个时间内，会不停的执行setInterval方法来使表格自适应
			/*_this.config.intervalTime = _this.getParmByAttr("intervalTime") || 500;			//setinterval方法时间间隔，默认500ms
			 */
			_this.config.intervalTime = _this.getParmByAttr("intervalTime") || 100; //setinterval方法时间间隔，默认500ms
			_this.config.order = _this.getParmByAttr("order") == 1 ? true : false; // 是否启用排序功能
			_this.config.sortServer = _this.getParmByAttr("sort-server") == 1 ? true : false; // 是否启用排序功能
			_this.config.callback = OTable.SORT_CALLBACK;
		},
		//获取对象的类样式
		getClass: function() {
			var _this = this;
			this.classes = $(_this.target).attr("class");
		},
		//获取对象的Id
		getId: function() {
			var _this = this;
			OTable.ID_COUNT += 1;
			this.id = $(_this.target).attr("id") || OTable.ID_COUNT;
		},

		//添加排序图标
		initSortOrder: function() {
			var _this = this;
			if(_this.config.order) {
				new MaxTableSort({
					table: $('#' + _this.tableWraperId),
					class_common: OTable.TABLE_SORT.CLASS_COMMON + ' ' + OTable.ORDER_SPAN_CLASS,
					path: OTable.TABLE_SORT.PIC_PATH,
					pic_default: OTable.TABLE_SORT.PIC_DEFAULT,
					pic_asc: OTable.TABLE_SORT.PIC_ASC,
					pic_desc: OTable.TABLE_SORT.PIC_DESC,
					class_default: OTable.TABLE_SORT.CLASS_DEFAULT,
					class_asc: OTable.TABLE_SORT.CLASS_ASC,
					class_desc: OTable.TABLE_SORT.CLASS_DESC,
					rule_default: OTable.TABLE_SORT.RULE_DEFAULT,
					rule_asc: OTable.TABLE_SORT.RULE_ASC,
					rule_desc: OTable.TABLE_SORT.RULE_DESC,
					id_name: OTable.TABLE_SORT.ID_NAME,
					sort_server: OTable.TABLE_SORT.SORT_SERVER,
					callback: function(order, field) {
						_this.sortOrder = order;
						_this.sortField = field;
						_this.config.callback && _this.config.callback(order, field);
						console.log(order, field)
					}
				});
			}
		},

		//创建表格标题
		creatCaption: function() {
			var _this = this;
			var ctable = $("<table></table>");
			ctable.addClass(_this.classes);
			ctable.append(_this.target.find("caption").clone());
			_this.caption.append(ctable);
		},
		//创建thead
		creatHeader: function() {
			//创建表头之前，先给表头固定高度
			var _this = this;
			_this.initSortOrder();
			var htable = $("<table></table>");
			htable.addClass(_this.classes);
			htable.append(_this.target.find("thead").clone());
			_this.header.append(htable);
		},
		//创建tbody
		creatBody: function() {
			var _this = this,
				tbody = $("<table></table>");
			tbody.addClass(_this.classes);
			tbody.attr("id", _this.id);
			tbody.append(_this.target.html());
			_this.body.append(tbody);
		},
		//创建tfoot
		creatFooter: function() {
			var _this = this;
			var ftable = $("<table></table>");
			ftable.addClass(_this.classes);
			ftable.append(_this.target.find("tfoot").clone());
			_this.footer.append(ftable);
		},
		//根据模版设置分页栏
		creatPagination: function(cb) {
			var _this = this;
			var paginationTmp = ""
			if(_this.config.paginationId) {
				paginationTmp = $("#" + _this.config.paginationId).html();
				_this.pagination.append(paginationTmp);
			} else if(_this.config.paginationUrl) {
				$.ajax({
					type: "get",
					url: _this.config.paginationUrl,
					success: function(data) {
						paginationTmp = data;
						_this.pagination.append(paginationTmp);
					}
				});
			}

		},
		//根据id创建工具栏
		creatToolBar: function() {
			var _this = this;
			var toolBarIdTmp = "";
			var toolBarId = _this.config.toolBarId;
			if(toolBarId) {
				toolBarIdTmp = $("#" + toolBarId).html();
				_this.toolbar.html(toolBarIdTmp);
				//移除工具栏模版
				$("#" + toolBarId).remove();
			} else if(_this.config.toolBarUrl) {
				$.ajax({
					type: "get",
					url: _this.config.toolBarUrl,
					success: function(data) {
						toolBarIdTmp = data;
						_this.toolbar.html(toolBarIdTmp);
					}
				});
			}
		},

		iniTable: function() {
			var _this = this;
			_this.target.removeAttr("data-initable");

			//根据原table的id设置tableWraper的id
			_this.tableWraperId = "tableWraper_" + _this.id;
			_this.tableWraper.attr("id", _this.tableWraperId);
			_this.target.wrap(_this.tableWraper);

			_this.target.wrap(_this.container);

			//创建内容区
			_this.target.wrap(_this.body);

			//创建header html
			if(_this.hasThead) {
				_this.target.find("thead").css({
					//	"visibility":"hidden"
				});
				_this.header.css("visibility", "hidden");
				_this.creatHeader();
				_this.target.parent().before(_this.header);
				_this.header.find("table").css({
					"width": "100%"
				});
				if(_this.target.find("thead tr:first").outerHeight() == _this.header.find("thead tr:first").outerHeight()) {
					_this.header.find("table").css({
						"visibility": "visible"
					});
					_this.header.css({
						"visibility": "visible"
					})
				}
				//绑定全选功能
				_this.header.find("tr").each(function() {
					if($(this).find("th:first input[type='checkbox']").length) {
						$(this).find("th:first input[type='checkbox']").addClass(OTable.CHECKBOX_CLASS.headCheckBox);
					}
				});
			}

			//创建tfoot
			if(_this.hasTfoot) {
				//将原table的tfoot设置隐藏
				_this.target.find("tfoot").css({
					"visibility": "hidden"
				});
				//创建footer html，并设置可见
				_this.creatFooter();
				_this.footer.find("tfoot").css({
					"visibility": "visible"
				});
				_this.target.parent().after(_this.footer);
			}

			//创建工具栏
			_this.creatToolBar();
			_this.target.parent().parent().before(_this.toolbar);

			//创建caption
			if(_this.hasCaption) {
				_this.creatCaption();
				_this.target.parent().parent().before(_this.caption);
			}

			//清除浮动
			_this.target.parent().parent().after("<div class='clearfix'></div>");
			//创建分页栏
			_this.creatPagination();
			_this.target.parent().parent().after(_this.pagination);

			_this.body.find("tfoot").css({
				"visibility": "hidden"
			});

			_this.target.parent().find("thead tr").each(function() {
				if($(this).find("th:first input[type='checkbox']").length) {
					$(this).find("th:first input[type='checkbox']").addClass(OTable.CHECKBOX_CLASS.headTriggerCheckBox);
				}
			});

			_this.winResize();
			_this.events();
			_this.stopResize();
			//表头，表尾的定时自适应
			_this.timer = "";
			_this.initResize();

			_this.timer = setInterval(function() {
				_this.initResize();
			}, _this.config.intervalTime);
			_this.oneTimer = setTimeout(function() {
				//显示表头
				_this.header.css({
					"visibility": "visible"
				});
				_this.header.find("thead").css({
					"visibility": "visible"
				});
			}, _this.config.intervalTime);
			setTimeout(function() {
				clearInterval(_this.timer);
			}, _this.config.outTime);
		},
		//重置表格，自适应
		initResize: function() {
			var _this = this,
				id = _this.tableWraperId,
				toolbar = _this.toolbar,
				container = _this.target.parent().parent(),
				header = _this.header,
				body = _this.target.parent(),
				footer = _this.footer,
				pagination = _this.pagination;

			var tableJson = {};
			var basicTable = $("#" + _this.id);
			//表格的宽度
			tableJson.width = basicTable.width() + 2;
			//caption的高度
			tableJson.captionH = basicTable.find("caption").outerHeight();
			//thead的整体高度
			tableJson.theadH = basicTable.find("thead").outerHeight();
			//tfoot的整体高度
			tableJson.tfootH = basicTable.find("footer").outerHeight();

			//toolBar的高度
			var toolbarH = toolbar.outerHeight();
			//pagination的高度
			var paginationH = pagination.outerHeight();
			body.css({
				"margin-top": tableJson.theadH
			});

			if(_this.config.height) {
				body.css({
					"height": _this.config.height - tableJson.captionH - tableJson.theadH - toolbarH - paginationH - 4
				})
			};

			if(_this.config.minHeight) {
				body.css({
					"min-height": parseInt(_this.config.minHeight)
				})
			};
			//如果设置了最小高度

			_this.initHeader();

			_this.initFooter();

			//绑定是否全选
			body.find("tbody tr").each(function(i) {
				if($(this).find("td:first input[type='checkbox']").length) {
					$(this).find("td:first input[type='checkbox']").addClass(OTable.CHECKBOX_CLASS.bodyCheckBox);
				};
			});

		},
		//header自适应
		initHeader: function() {
			var _this = this,
				header = _this.header;
			var basicTable = $("#" + _this.id);
			var tableJson = {};
			//表格的宽度
			/*tableJson.width = basicTable.width()+2;*/
			tableJson.width = _this.target.width() + 2;
			//caption的高度
			tableJson.captionH = basicTable.find("caption").outerHeight();
			//thead的整体高度
			tableJson.theadH = basicTable.find("thead").outerHeight();
			//thead的行宽度和高度

			var theadArr = [];
			basicTable.find("thead tr").each(function() {
				var trJson = {};
				var thArr = [];
				$(this).children("th").each(function(n) {
					thArr.push($(this).outerWidth());
				});
				trJson.height = $(this).outerHeight();
				trJson.ths = thArr;
				theadArr.push(trJson);
			});
			//	console.log("tableJson.width----》"+tableJson.width)
			if(tableJson.width > 300) {
				header.css({
					"width": tableJson.width
				});
			}
			basicTable.css({
				"margin-top": -tableJson.theadH - tableJson.captionH
			});
			var newHeadTable = header.find("table");
			newHeadTable.find("tr").each(function(n) {
				var trData = theadArr[n];
				if(trData.height != 0) {
					$(this).css({
						"height": trData.height
					})
				}
				$(this).children("th").each(function(m) {
					if(trData.ths[m] != 0) {
						$(this).css({
							"width": trData.ths[m]
						})
					}
				});
			});
		},
		//footer自适应
		initFooter: function() {
			var _this = this,
				footer = _this.footer;
			var basicTable = $("#" + _this.id);
			var tableJson = {};
			//表格的宽度
			tableJson.width = basicTable.width() + 2;
			tableJson.tfootH = basicTable.find("tfoot").outerHeight();
			//thead的行宽度和高度
			var tfootArr = [];
			basicTable.find("tfoot tr").each(function() {
				var trJson = {};
				var thArr = [];
				$(this).children("td").each(function() {
					thArr.push($(this).outerWidth());
				});
				trJson.height = $(this).outerHeight();
				trJson.ths = thArr;
				tfootArr.push(trJson);
			});

			footer.css({
				"width": tableJson.width
			});
			var newHeadTable = footer.find("table");
			newHeadTable.find("tr").each(function(n) {
				var trData = tfootArr[n];
				/*$(this).css({
					"height":trData.height
				})*/
				$(this).children("td").each(function(m) {
					$(this).css({
						"width": trData.ths[m]
					})
				});
			});
		},
		//窗口改变，表格自适应
		winResize: function() {
			var _this = this;

			_this.timeout = "";
			$(window).on("resize", function() {
				clearTimeout(_this.timeout);
				_this.timeout = setTimeout(function() {
					_this.initResize();
					_this.config.height = $("#" + _this.tableWraperId + " .maxTable_body table").attr("data-height");
					//表头，表尾的定时自适应
					_this.timer = "";
					_this.stopResize();
					_this.timer = setInterval(function() {
						_this.initResize();
					}, _this.config.intervalTime);
					setTimeout(function() {
						clearInterval(_this.timer);
					}, _this.config.outTime);
				}, _this.config.intervalTime);
			})
		},
		//刷新，根据参数
		reflesh: function(height) {
			var _this = this;
			_this.stopResize();
			if(height) {
				this.config.height = height;
				this.target.attr("data-height", height);
			}
			_this.timer = "";
			_this.timer = setInterval(function() {
				_this.initResize();
			}, _this.config.intervalTime);
			setTimeout(function() {
				clearInterval(_this.timer);
			}, _this.config.outTime);
		},
		//停止刷新
		stopResize: function() {
			clearInterval(this.timer);
			clearInterval(this.timeout);
			clearInterval(this.config.intervalTime);
			clearTimeout(this.config.outTime)
		},
		events: function() {
			var _this = this;
			//绑定全选
			if(_this.hasThead) {

				_this.header.find("thead *").each(function() {
					$(this).removeAttr("onclick onchange ondblClick id") //.off();
				});

				$(document).on("click", "#" + _this.tableWraperId + " .maxTable_header thead *:not(input[type='checkbox']." + OTable.CHECKBOX_CLASS.headCheckBox + ")", function(e) {
					var ev = e || window.event;
					ev.preventDefault()
					ev.stopPropagation();
					var par = $(this).parents("#" + _this.tableWraperId);
					var index = $(this).index("#" + _this.tableWraperId + " .maxTable_header thead *:not(input[type='checkbox']." + OTable.CHECKBOX_CLASS.headCheckBox + ")");
					par.find(".maxTable_body thead *:not(input[type='checkbox']." + OTable.CHECKBOX_CLASS.headTriggerCheckBox + ")").eq(index).trigger("click");
				});

				$(document).on("click", "#" + _this.tableWraperId + " input[type='checkbox']." + OTable.CHECKBOX_CLASS.headCheckBox, function(e) {
					var ev = e || window.event;
					ev.stopPropagation();
					var par = $(this).parents("#" + _this.tableWraperId);
					var index = $(this).index("#" + _this.tableWraperId + " .maxTable_header table input[type='checkbox']." + OTable.CHECKBOX_CLASS.headCheckBox);
					par.find(".maxTable_body table thead input[type='checkbox']." + OTable.CHECKBOX_CLASS.headTriggerCheckBox).eq(index).trigger("click");
					_this.methods.checkAll.call(_this, this);
				});
			}

			//绑定是否全选
			$(document).on("click", "input[type='checkbox']." + OTable.CHECKBOX_CLASS.bodyCheckBox, function() {
				var checked = $(this).prop("checked");
				if(checked) {
					$(this).parents("tr").addClass("active");
				} else {
					$(this).parents("tr").removeClass("active");
				}
				_this.methods.isCheckAll.call(_this, this);
			});
		},
		methods: {

			//多选框全选
			checkAll: function(obj) {
				var _this = this;
				var headCheckBox = $(obj);
				var checked = headCheckBox.prop("checked");
				var par = $(obj).parents("#" + _this.tableWraperId);
				par.find("tbody input[type]." + OTable.CHECKBOX_CLASS.bodyCheckBox).each(function() {
					$(this).prop("checked", checked);
					if(checked) {
						$(this).parents("tr").addClass("active");
					} else {
						$(this).parents("tr").removeClass("active");
					}
				});
			},
			//是否全选
			isCheckAll: function(obj) {
				var _this = this;
				var checked = $(obj).prop("checked");
				var par = $(obj).parents("#" + _this.tableWraperId);
				if(!checked) {
					par.find("input[type]." + OTable.CHECKBOX_CLASS.headCheckBox).prop("checked", false);
				} else { //判断是否有为选中的项
					var mark = true;
					par.find("tbody input[type]." + OTable.CHECKBOX_CLASS.bodyCheckBox).each(function() {
						if(!$(this).prop("checked")) {
							mark = false;
						}
						if(!mark) {
							return false;
						}
					});
					par.find("input[type]." + OTable.CHECKBOX_CLASS.headCheckBox).prop("checked", mark);
				}
			}
		}
	};

	OTable.TABLE_SORT = {
		PIC_PATH: './',
		PIC_DEFAULT: 'table_default.png',
		PIC_ASC: 'table_asc.png',
		PIC_DESC: 'table_desc.png',
		CLASS_COMMON: '',
		CLASS_DEFAULT: 'table_default',
		CLASS_ASC: 'table_asc',
		CLASS_DESC: 'table_desc',
		RULE_DEFAULT: 0,
		RULE_ASC: 1,
		RULE_DESC: 2,
		ID_NAME: 'tableSort_',
		ID: 0,
		SSORT_SERVER: false
	};
	
	// 初始化排序参数
	win.MaxTable_initParm = function(options){
		//设置默认公共类样式
		OTable.CLASS_COMMON = options && options.class_common;
		//设置排序的回调函数
		OTable.SORT_CALLBACK = options && options.callback;
		OTable.TABLE_SORT = {
			PIC_PATH: options && options.path || './',
			PIC_DEFAULT: options && options.pic_default || 'table_default.png',
			PIC_ASC: options && options.pic_asc || 'table_asc.png',
			PIC_DESC: options && options.pic_desc || 'table_desc.png',
			CLASS_COMMON: options && options.class_common || '',
			CLASS_DEFAULT: options && options.class_default || 'table_default',
			CLASS_ASC: options && options.class_asc || 'table_asc',
			CLASS_DESC: options && options.class_desc || 'table_desc',
			RULE_DEFAULT: options && options.rule_default || 0,
			RULE_ASC: options && options.rule_asc ||  1,
			RULE_DESC: options && options.rule_desc||  2,
			ID_NAME: options && options.id_name ||  'tableSort_',
			ID: 0,
			SORT_SERVER: options && options.sort_server || false	//是否前端排序，默认是
		};
	};
	
	win.MaxTableInit = function(collection) {
		if(!collection) {
			collection = $("table[data-initable='yes']");
		}
		collection.each(function(n) {
			new OTable($(this));
		});
	};

	win.MaxTable = OTable;

})(window, jQuery);